package cn.pengpeng.day04.index;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;

import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;



/**
 * 倒排索引
 * hello tom
 * 
 * hello-a 1
 * tom-a 1
 * 
 * 
 * hello jim
 * 
 * hello -->文件1中出现多少次，在文件2中出现多少次
 * @author root
 * 
 *
 */
public class CreateIndexOne {
	public static class MapTask extends Mapper<LongWritable, Text, Text, IntWritable>{
		String fileName = null;
		@Override
		protected void setup(Mapper<LongWritable, Text, Text, IntWritable>.Context context)
				throws IOException, InterruptedException {
			FileSplit fileSplit = (FileSplit)context.getInputSplit();
			fileName = fileSplit.getPath().getName();
		}
		
		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context)
				throws IOException, InterruptedException {
			String[] split = value.toString().split(" ");
			
			for (String word : split) {
				context.write(new Text(word+"-"+fileName), new IntWritable(1));
			}
		}
	}
	
	public static class ReduceTask extends Reducer<Text, IntWritable, Text, IntWritable>{
		@Override
		protected void reduce(Text key, Iterable<IntWritable> values,
				Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
			int count = 0;
			for (IntWritable intWritable : values) {
				count++;
			}
			context.write(key, new IntWritable(count));
		}
	}
	
	public static void main(String[] args) throws Exception{
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);
		
		//设置job的map 和 reduce 是哪一个 提交任务的类
		job.setMapperClass(MapTask.class);
		job.setReducerClass(ReduceTask.class);
		job.setJarByClass(CreateIndexOne.class);
		
		//设置输出的类型
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(IntWritable.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		
		job.setNumReduceTasks(2);
		
		
		//设置输入目录和输出目录
		FileInputFormat.addInputPath(job, new Path("D:/in/index"));
		FileOutputFormat.setOutputPath(job, new Path("d:/out/index1"));
		
		
		File file = new File("d:/out/index1");
		if(file.exists()){
			FileUtils.deleteDirectory(file);
		}
		
		//提交任务并等待任务结束，能够打印日志
		boolean waitForCompletion = job.waitForCompletion(true);
		System.out.println(waitForCompletion?"程序正常退出":"程序有问题了");	
	}
}
